package com.citsin.atlas.viewmodel

import android.content.ContentResolver
import android.provider.MediaStore
import androidx.paging.PositionalDataSource
import com.citsin.atlas.bean.Album

/**
 * 2019-06-04
 */
private const val  COLUMN_COUNT = "count"
class AlbumDataSource(private val contentResolver: ContentResolver) :
    PositionalDataSource<Album>() {
    companion object{
        private val QUERY_URI = MediaStore.Files.getContentUri("external")
    }

    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Album>) {
    }

    override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Album>) {
        val projection = arrayOf(
            MediaStore.Files.FileColumns._ID,
            "bucket_id",
            "bucket_display_name",
            MediaStore.MediaColumns.DATA,
            "COUNT(*) AS $COLUMN_COUNT")
        val selection =
            "(${MediaStore.Files.FileColumns.MEDIA_TYPE}=? OR ${MediaStore.Files.FileColumns.MEDIA_TYPE}=?)" +
                    " AND ${MediaStore.MediaColumns.SIZE}>0) GROUP BY (bucket_id"
        val selectionArgs = arrayOf(
            MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString(),
            MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString())
        val  bucketOrderBy = "datetaken DESC"
        val albums: MutableList<Album> = mutableListOf()
        val cursor = contentResolver.query(QUERY_URI, projection, selection, selectionArgs, bucketOrderBy)
        if (cursor == null){
            callback.onResult(albums,0)
            return
        }
        while (cursor.moveToNext()){
            val id  = cursor.getString(1)
            val displayName = cursor.getString(2)
            val data = cursor.getString(3)
            albums.add(Album(id,displayName,data))
        }
        callback.onResult(albums,0)

    }
}
